package com.qiu.greened.ui.post

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.INgvImageLoader
import com.lwkandroid.widget.ngv.NgvChildImageView
import com.qiu.greened.adapter.ReplyAdapter
import com.qiu.greened.bean.FollowBean
import com.qiu.greened.bean.ReplyPostBean
import com.qiu.greened.bean.StarBean
import com.qiu.greened.databinding.ActivityPostInfoBinding
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.getTimeFormatText
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.*

/**
 * 动态页 评论页
 */
class PostInfoActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPostInfoBinding
    private val viewModel: PostInfoViewModel by viewModels()
    private val replyAdapter by lazy { ReplyAdapter() }
    private lateinit var ngvAdapter: DefaultNgvAdapter<String>

    private var postUserId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPostInfoBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //标题栏
        supportActionBar?.let {
            it.setHomeButtonEnabled(true)
            it.setDisplayHomeAsUpEnabled(true)
            it.title = "动态详情"
        }
        val postId: Int = intent.getIntExtra("postId", -1)
        setPostData(postId) //设置动态数据
        setReplyData(postId) //设置评论数据
        //关注按钮
        binding.btnFollow.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val follow = FollowBean(MyData.userId, postUserId)
                    val result =
                        ServiceCreator.create<UserService>().setFollow(MyData.token, follow)
                    if (result.msg == "insert") {
                        setFollowView(true)
                    } else if (result.msg == "delete") {
                        setFollowView(false)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    "${e.message}".showToast()
                    Log.i("请求失败", "${e.message}")
                }
            }
        }
        //点赞按钮
        binding.btnStar.setOnClickListener {
            lifecycleScope.launch {
                try {
                    val data = ServiceCreator.create<PostService>()
                        .setStar(MyData.token, StarBean(MyData.userId, postId))
                    binding.textStar.text = when (data.msg) {
                        "insert" -> (binding.textStar.text.toString().toInt() + 1).toString()
                        "delete" -> (binding.textStar.text.toString().toInt() - 1).toString()
                        else -> binding.textStar.text.toString()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    "${e.message}".showToast()
                    Log.i("请求失败", "${e.message}")
                }
            }
        }
        //评论按钮
        binding.btnSend.setOnClickListener {
            val content = binding.editText.text.toString()
            if (content == "") {
                "评论为空".showToast()
            } else {
                lifecycleScope.launch {
                    try {
                        val reply = ReplyPostBean(MyData.userId, postId, content, postUserId)
                        val result =
                            ServiceCreator.create<PostService>().setReply(MyData.token, reply)
                        if (result.code == 200) {
                            "发布成功".showToast()
                            binding.editText.setText("")
                            val inputMethodManager =
                                this@PostInfoActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                            inputMethodManager.hideSoftInputFromWindow(
                                binding.root.windowToken,
                                InputMethodManager.HIDE_NOT_ALWAYS
                            )
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        "${e.message}".showToast()
                        Log.i("请求失败", "${e.message}")
                    }
                }
            }
        }
    }

    /**
     * 设置动态数据
     */
    private fun setPostData(postId: Int) {
        viewModel.loadPost(postId)
        viewModel.post.observe(this, {
            postUserId = it.userId
            binding.textName.text = it.nickName
            binding.textContent.text = it.postContent
            binding.textStar.text = it.postStar.toString()
            binding.textTime.text = getTimeFormatText(it.createTime)
            Glide.with(this).load(ServiceCreator.BASE_URL + it.userAvatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop())).into(binding.imgUser)
            binding.btnStar.isChecked = it.isStar
            if (it.userId == MyData.userId) {
                binding.btnFollow.visibility = View.INVISIBLE
            } else {
                setFollowView(it.isFollow)
            }
            Log.d("null", it.postImg)
            if (it.postImg != "") {
                setImage(it.postImg)
            }
        })
    }

    private fun setImage(postImg: String) {
        //创建图片加载器
        class GlideDisplay : INgvImageLoader<String> {
            override fun load(url: String, imageView: ImageView, width: Int, height: Int) {
                Glide.with(imageView.context)
                    .load(ServiceCreator.BASE_URL + url)
                    .apply(
                        RequestOptions().override(width, height)
                            .transform(CenterCrop(), RoundedCorners(10))
                    )
                    .into(imageView)
            }
        }
        //NineGridView的数据适配器，构造方法中必须设置最大数据容量和图片加载器
        ngvAdapter = DefaultNgvAdapter(9, GlideDisplay())
        ngvAdapter.setOnChildClickListener(object :
            DefaultNgvAdapter.OnChildClickedListener<String> {
            override fun onContentImageClicked(
                position: Int, data: String, childImageView: NgvChildImageView?
            ) {
                Log.d("image", data)
                //点击图片时的回调
            }

            override fun onPlusImageClicked(plusImageView: ImageView, dValueToLimited: Int) {}
            override fun onImageDeleted(position: Int, data: String) {}
        })
        binding.gridView.adapter = ngvAdapter
        val serList = postImg.split("&")
        ngvAdapter.addDataList(serList)
    }

    /**
     * 设置评论数据
     */
    private fun setReplyData(postId: Int) {
        val linearLayoutManager = LinearLayoutManager(this)
        binding.recyclerView.layoutManager = linearLayoutManager
        binding.recyclerView.adapter = replyAdapter
        binding.recyclerView.addItemDecoration(
            DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
        )
        lifecycleScope.launch {
            viewModel.getPagingData(postId).collect { pagingData ->
                replyAdapter.submitData(pagingData)
            }
        }
        replyAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    "Load Error: ${state.error.message}".showToast()
                }
            }
        }
        replyAdapter.addOnPagesUpdatedListener {
            binding.recyclerView.scrollToPosition(0)
        }
    }

    private fun setFollowView(bool: Boolean) {
        if (bool) {
            binding.btnFollow.text = "取消关注"
        } else {
            binding.btnFollow.text = "关注"
        }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish() // back button
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}

